package com.uxsino.commons.utils.config;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.function.Consumer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FileResourceWalker implements IResourceWalker {
    private static Logger logger = LoggerFactory.getLogger(FileResourceWalker.class);

    String path;

    String fileExtension;

    public FileResourceWalker(String path, String fileExtension) {
        this.path = path;
        this.fileExtension = fileExtension;
    }

    @Override
    public void forEach(Consumer<URL> action) throws IOException {
        Files.walk(Paths.get(path)).forEach(f -> {
            try {
                try {
                    if ((!Files.isRegularFile(f)) || Files.isHidden(f)) {
                        return;
                    }
                } catch (IOException e) {
                    return;
                }
                // .xxx file doesn't mean hidden in windows, so ignore it
                // explicitly.

                String fileName = f.getFileName().toString();
                if ((!fileName.endsWith(fileExtension)) || fileName.startsWith(".")) {
                    return;
                }

                action.accept(f.toUri().toURL());
            } catch (MalformedURLException e) {
                logger.error("error in file url:{}", e);
            }
        });
    }

}
